import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useUserStore } from './useUserStore'
import api from '@/api/request'

export const useExperimentStore = defineStore(
  'experimentStore',
  () => {
    const userStore = useUserStore()

    // 存储历史实验列表
    const historyExperiments = ref([])
    // 当前选中的实验
    const currentExperiment = ref(null)
    // 收集的实验数据
    const collectedExperiments = ref({})

    // 使用 ref 定义 teamName 响应式状态
    const teamName = ref('')
    const teamOptions = ref([])

    // 获取团队列表
    const fetchTeamList = async () => {
      try {
        const response = await api.post('/userteam', null, {
          headers: {
            'Content-Type': 'application/json',
            token: userStore.token
          }
        })

        if (response.data && response.data.code === 200) {
          // 转换数据格式为 options 数组
          teamOptions.value = response.data.data.map((teamName) => ({
            value: teamName,
            label: teamName
          }))

          // 如果有团队数据且当前teamName为空，设置第一个团队为当前团队
          if (teamOptions.value.length > 0 && !teamName.value) {
            teamName.value = teamOptions.value[0].value
          }
        }
      } catch (error) {
        console.error('获取团队列表失败:', error)
      }
    }

    // setTeamName 方法，更新 teamName 状态
    const setTeamName = (newTeamName) => {
      teamName.value = newTeamName
    }

    // 获取团队下的所有实验名称
    const fetchTeamExperiments = async () => {
      try {
        await fetchTeamList() // 确保团队列表已获取

        // 获取团队实验数据
        const response = await api.post('/teamIdexperiments', null, {
          params: {
            teamName: teamName.value
          },
          headers: {
            'Content-Type': 'application/json',
            token: userStore.token
          },
          withCredentials: true
        })

        console.log('响应数据:', response.data) // 调试输出

        // 将字符串转换为对象数组
        if (response.data && response.data.data) {
          historyExperiments.value = response.data.data.map((name, index) => ({
            id: index + 1, // 使用索引作为 id
            name: name
          }))
        } else {
          console.error('数据结构不正确:', response.data)
        }

        console.log('历史实验名称:', historyExperiments.value) // 调试输出
      } catch (error) {
        console.error('获取团队实验失败:', error)
      }
    }

    const fetchHistoryExperiments = async (experimentName) => {
      try {
        console.log('请求实验名称:', experimentName)

        const response = await api.post(
          '/history',
          { experimentName },
          {
            headers: {
              'Content-Type': 'application/json',
              token: userStore.token
            },
            withCredentials: true
          }
        )

        console.log('API 响应数据:', response)
        console.log('API 返回的 data:', response.data)
        console.log('API 返回的 data.data:', response.data?.data)

        if (response.data?.data) {
          historyExperiments.value = response.data.data
          console.log('✅ 历史实验数据已存入:', historyExperiments.value)
        } else {
          console.error('❌ API 返回数据格式错误:', response)
        }
      } catch (error) {
        console.error('❌ 获取历史实验失败:', error)
        throw error
      }
    }

    // 创建新实验（自动关联到当前团队）
    const createExperiment = async (experimentData) => {
      try {
        const response = await axios.post(
          '/new',
          {
            ...experimentData,
            teamId: userStore.currentTeam?.id
          },
          {
            headers: {
              'Content-Type': 'application/json',
              token: userStore.token
            },
            withCredentials: true
          }
        )
        return response.data
      } catch (error) {
        console.error('创建实验失败:', error)
        throw error
      }
    }

    // 选择实验
    const selectExperiment = (experiment) => {
      currentExperiment.value = experiment
    }

    // 更新实验数据
    const updateExperimentData = (data) => {
      collectedExperiments.value = data
    }

    // 定义清空数据的方法
    const reset = () => {
      collectedExperiments.value = {
        experimentName: '',
        experimentRounds: []
      }
    }

    // 收集实验数据
    const collectExperiments = (experimentData) => {
      collectedExperiments.value = experimentData
    }

    // 修改 selectHistoryExperiment 函数
    const selectHistoryExperiment = async (experiment) => {
      try {
        const response = await api.post(
          '/history',
          {
            experimentName: experiment.name
          },
          {
            headers: {
              'Content-Type': 'application/json',
              token: userStore.token
            },
            withCredentials: true
          }
        )

        // 确保 currentExperiment 被正确设置
        if (response.data?.data) {
          currentExperiment.value = response.data.data
          console.log('当前选中的实验:', currentExperiment.value)

          // 更新 historyExperiments 以便在界面上展示
          historyExperiments.value = response.data.data.experimentRounds || []
        } else {
          console.error('❌ API 返回数据格式错误:', response)
        }
      } catch (error) {
        console.error('❌ 获取历史实验失败:', error)
        throw error
      }
    }

    // 在组件挂载时获取团队实验
    onMounted(() => {
      fetchTeamExperiments()
    })

    // 返回状态和动作
    return {
      historyExperiments,
      currentExperiment,
      collectedExperiments,
      teamName,
      teamOptions,
      setTeamName,
      fetchTeamList,
      fetchTeamExperiments,
      fetchHistoryExperiments,
      createExperiment,
      selectExperiment,
      updateExperimentData,
      reset,
      collectExperiments,
      selectHistoryExperiment
    }
  },
  {
    persist: {
      enabled: true,
      strategies: [
        {
          key: 'collectedExperiments',
          storage: localStorage // 使用 localStorage 来存储数据
        },
        {
          key: 'teamName',
          storage: localStorage // 使用 localStorage 来持久化存储数据
        }
      ]
    }
  }
)
